package com.yao.smy.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * 局域网设备扫描服务实现类
 */
@Service
public class DeviceScannerServiceImpl implements DeviceScannerService {

    private List<String> onlineDevices = new ArrayList<>();

    /**
     * 定时扫描局域网内的设备，每10分钟执行一次
     */
    @Scheduled(fixedRate = 300000) // 600000毫秒 = 10分钟
    public void scheduledScanLocalNetwork() {
        onlineDevices = scanLocalNetwork();
    }

    /**
     * 扫描局域网内的设备
     * @return 在线设备的IP地址列表
     */
    @Override
    public List<String> scanLocalNetwork() {
        List<String> onlineDevices = new ArrayList<>();
        String localIp = getLocalIpAddress();
        String subnet = localIp.substring(0, localIp.lastIndexOf('.'));

        for (int i = 1; i <= 255; i++) {
            String host = subnet + "." + i;
            try {
                Process process = Runtime.getRuntime().exec("ping -c 1 -W 200 " + host);
                int exitCode = process.waitFor();
                if (exitCode == 0) {
                    onlineDevices.add(host);
                }
            } catch (Exception e) {
                // 忽略无法访问的设备
            }
        }

        return onlineDevices;
    }

    /**
     * 获取当前在线设备列表
     * @return 在线设备的IP地址列表
     */
    @Override
    public List<String> getOnlineDevices() {
        return onlineDevices;
    }

    /**
     * 获取本机IP地址
     * @return 本机IP地址
     */
    private String getLocalIpAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw new RuntimeException("无法获取本机IP地址", e);
        }
    }
}
